﻿using System.Linq;

namespace ECommerce.Administration
{
	public class AdminLocalLizationManager
	{
		private static Service.LocalStringResourceService _LocalStringResourceService;
		private static Service.LanguageService _LanguageService;

		public static string GetLocalResourceString(string name)
		{
			if (string.IsNullOrEmpty(name))
			{
				return string.Empty;
			}

			//if (SiteContext.Current != null && SiteContext.Current.WorkingLanguage != null)
			//{
			//var currentLanguage = SiteContext.Current.WorkingLanguage;

			if (_LanguageService == null)
			{
				_LanguageService = new Service.LanguageService();
			}

			if (_LocalStringResourceService == null)
			{
				_LocalStringResourceService = new Service.LocalStringResourceService();
			}

			var allLanguage = _LanguageService.GetAllLanguage();

			if (allLanguage != null)
			{
				var lang = (from l in allLanguage
							where l.LanguageCulture.Equals("zh-CN")
							select l).FirstOrDefault();

				if (lang != null)
				{
					var localStrings = _LocalStringResourceService.GetLocaleStringResourceByLanguage(lang.LanguageId);

					var ls = (from v in localStrings
							  where v.ResourceName == name
							  select v.ResourceValue).FirstOrDefault();

					if (ls != null && ls.Count() > 0)
					{
						var rv = ls.ToString();

						return ls;
					}
				}
			}
			//}

			return string.Empty;
		}

		public static void ChangeCurrentCulture(int languageID)
		{
			if (languageID > 0)
			{
				if (_LanguageService == null)
				{
					_LanguageService = new Service.LanguageService();
				}

				var theCurrentLanguage = (from l in _LanguageService.GetAllLanguage()
										  where l.LanguageId.Equals(languageID)
										  select l).FirstOrDefault();

				if (theCurrentLanguage != null)
				{
					var culture = new System.Globalization.CultureInfo(theCurrentLanguage.LanguageCulture);
					System.Threading.Thread.CurrentThread.CurrentCulture = culture;
					System.Threading.Thread.CurrentThread.CurrentUICulture = culture;

					SiteContext.Current.SetCookie(SiteContext.COOKIE_KEY_LANGUAGECULTURE, theCurrentLanguage.LanguageCulture);
					SiteContext.Current.WorkingLanguage = theCurrentLanguage;
				}
			}
		}
	}
}
